<template>
  <div class="app-container">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span class="title">产品目录管理</span>
          <el-button type="primary" :icon="Plus" @click="handleAdd">新增目录</el-button>
        </div>
      </template>

      <el-table :data="tableData" border v-loading="loading" class="main-table" stripe>
        <template #empty>
          <el-empty description="暂无目录，请点击右上角新增" />
        </template>
        <el-table-column prop="index" width="100" label="序号" />
        <el-table-column prop="name" label="目录名称" />
        <el-table-column label="封面图" width="120" align="center">
          <template #default="scope">
            <el-image 
              class="cover-image"
              :src="scope.row.coverImage" 
              :preview-src-list="[scope.row.coverImage]"
              fit="cover" 
              preview-teleported
            />
          </template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序值" width="120" align="center" />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" link :icon="Edit" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link :icon="Delete" size="small" @click="handleDelete(scope.row._id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-if="pagination.total > 0"
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchData"
          @current-change="fetchData"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="handleDialogClose" :close-on-click-modal="false" top="8vh">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="目录名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入目录名称" />
        </el-form-item>
        <el-form-item label="排序值">
          <el-input-number v-model="form.sortOrder" :min="0" />
        </el-form-item>
        <el-form-item label="封面图" prop="coverImage">
          <el-upload
            class="cover-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :before-upload="beforeImageUpload"
          >
            <img v-if="form.coverImage" :src="form.coverImage" class="cover" />
            <el-icon v-else class="uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="详情图片">
           <el-upload
            :action="uploadUrl"
            list-type="picture-card"
            :on-success="handleImagesSuccess"
            :on-remove="handleImagesRemove"
            :file-list="fileList"
            :before-upload="beforeImageUpload"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                可上传多张图片，单张图片大小不超过20MB。
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" :loading="submitting" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// <script>部分与上一版基本相同，这里为了简洁省略粘贴
// 您可以继续使用上一版功能完整的<script>代码
// 如果需要，我可以再次贴出
import { ref, reactive, onMounted, computed } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

// --- 状态定义 ---
const loading = ref(true);
const submitting = ref(false);
const tableData = ref([]);
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref(null);

const defaultForm = () => ({
  _id: '',
  name: '',
  sortOrder: 0,
  coverImage: '',
  images: [],
});
const form = reactive(defaultForm());

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api';
const uploadUrl = `${API_BASE_URL}/upload`;

const rules = reactive({
  name: [{ required: true, message: '请输入目录名称', trigger: 'blur' }],
  coverImage: [{ required: true, message: '请上传封面图', trigger: 'change' }],
});

const dialogTitle = computed(() => (isEdit.value ? '编辑目录' : '新增目录'));
const fileList = computed(() => form.images.map(url => ({ name: url, url })));

const fetchData = async () => {
  loading.value = true;
  try {
    const params = { page: pagination.currentPage, pageSize: pagination.pageSize };
    const res = await axios.get(`${API_BASE_URL}/categories`, { params });
    tableData.value = res.data.data.map((item, index) => ({
      ...item,
      index: index + 1,
    }));
    pagination.total = res.data.total;
  } catch (error) {
    ElMessage.error('获取目录列表失败');
  } finally {
    loading.value = false;
  }
};

const handleDelete = (id) => {
  ElMessageBox.confirm('数据删除后无法恢复，确定要删除吗?', '警告', {
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await axios.delete(`${API_BASE_URL}/categories/${id}`);
      ElMessage.success('删除成功');
      if (tableData.value.length === 1 && pagination.currentPage > 1) {
        pagination.currentPage--;
      }
      fetchData();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

const handleAdd = () => {
  isEdit.value = false;
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  isEdit.value = true;
  Object.assign(form, JSON.parse(JSON.stringify(row)));
  dialogVisible.value = true;
};

const handleDialogClose = () => {
  Object.assign(form, defaultForm());
  formRef.value?.resetFields();
};

const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        if (isEdit.value) {
          await axios.put(`${API_BASE_URL}/categories/${form._id}`, form);
          ElMessage.success('更新成功');
        } else {
          const { _id, ...newForm } = form;
          await axios.post(`${API_BASE_URL}/categories`, newForm);
          ElMessage.success('新增成功');
        }
        dialogVisible.value = false;
        fetchData();
      } catch (error) {
        ElMessage.error('操作失败');
      } finally {
        submitting.value = false;
      }
    } else {
      ElMessage.error('请检查表单必填项');
      return false;
    }
  });
  Object.assign(form, defaultForm());
  formRef.value?.resetFields();
};

const beforeImageUpload = (rawFile) => {
  const isJPGorPNG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png';
  const isLt2M = rawFile.size / 1024 / 1024 < 20;

  if (!isJPGorPNG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 20MB!');
  }
  return isJPGorPNG && isLt2M;
};

const handleCoverSuccess = (response) => {
  form.coverImage = response.url;
  formRef.value?.validateField('coverImage');
};

const handleImagesSuccess = (response) => {
  form.images.push(response.url);
};

const handleImagesRemove = (uploadFile) => {
  const index = form.images.indexOf(uploadFile.url);
  if (index > -1) {
    form.images.splice(index, 1);
  }
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
/* 全局容器和背景色 */
.app-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

/* 主卡片样式 */
.main-card {
  border: none;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header .title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

/* 表格样式 */
.main-table {
  width: 100%;
}

.main-table .cover-image {
  width: 70px;
  height: 70px;
  border-radius: 6px;
}

/* 使用 :deep() 来修改 Element Plus 子组件的样式 */
:deep(.el-table th.el-table__cell) {
  background-color: #fafafa !important;
  color: #606266;
  font-weight: 600;
}

:deep(.el-button.is-link) {
  font-size: 14px;
}

/* 分页容器 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}

/* 上传组件样式 */
.cover-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.cover-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px; /* picture-card的默认尺寸 */
  height: 148px;
  text-align: center;
}

.cover {
  width: 148px;
  height: 148px;
  display: block;
  object-fit: cover;
}

.el-upload__tip {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
}
</style>